import dayjs from "dayjs";
const uploadUrl = '/kingon-file/oss/endpoint/put-file?code=minio';
// console.log("uni.$kui.config: ", uni.$kui.config);
// 自定义验证函数 (放到一个文件，需要的话引入)
const validators = {
  phone: {
    validator: (rule, value, callback) => {
      if (!value) return true;
      return uni.$u.test.mobile(value);
    },
    message: '手机号码不正确',
    trigger: ['change', 'blur'],
  },
};
// 表单配置
const config = [
  {
    type: 'input',
    label: '输入框',
    key: 'input',
    placeholder: '请输入姓名',
    disabled: false,
    required: true,
    // initVal: '这是设置的默认值',
    initVal: () => {
      return '这是设置的默认值 function';
    },
    rules: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    comOption: {},
    hooks: {},
  },
  {
    type: 'input',
    label: '密码',
    key: 'input-password',
    placeholder: '请输入密码',
    disabled: false,
    required: true,
    rules: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '长度不可以小于6位' },
    ],
    comOption: {
      type: 'password',
      clearable: true,
      password: true, // 是否可以查看密码
    },
    hooks: {},
  },
  {
    type: 'input',
    label: '价格',
    key: 'input-price',
    placeholder: '请输入价格',
    required: false,
    rules: [],
    comOption: {
      type: 'number',
      // 'prefix-icon': 'warning-fill',
      'suffix-icon': '元',
      'suffix-icon-style': 'font-weight: bold;',
    },
    hooks: {},
  },
  {
    type: 'input',
    label: '手机号',
    key: 'input-phone',
    required: false,
    rules: [validators.phone],
    comOption: {
      type: 'number',
    },
  },
  { type: 'gap' },
  {
    type: 'radio',
    label: '单选',
    key: 'radio',
    required: false,
    initVal: '3',
    comOption: {
      columns: [
        { name: '是', value: '1', disabled: false },
        { name: '否', value: '0', disabled: false },
        { name: '非', value: '3' },
      ],
    },
    hooks: {},
  },
  {
    type: 'radio',
    label: '单选-请求接口',
    key: 'radio-dict',
    required: true,
    actions: '/kingon-system/dict/data/type/sys-educational-Level',
    comOption: {
      lableName: 'dictLabel',
      keyName: 'dictKey',
      // 当actions和columns同时存在时，actions请求优先于columns
      columns: [
        { name: '是', value: '1', disabled: false },
        { name: '否', value: '0', disabled: false },
        { name: '非', value: '3' },
      ],
    },
    hooks: {},
  },
  {
    type: 'checkbox',
    label: '多选',
    key: 'checkbox',
    initVal: '1,3',
    required: false,
    comOption: {
      columns: [
        { name: '是', value: '1', disabled: false },
        { name: '否', value: '0', disabled: false },
        { name: '非', value: '3' },
      ],
    },
    hooks: {},
  },
  {
    type: 'checkbox',
    label: '多选-请求接口',
    key: 'checkbox-dict',
    actions: '/kingon-system/dict/data/type/sys-educational-Level',
    required: true,
    comOption: {
      lableName: 'dictLabel',
      keyName: 'dictKey',
      columns: [
        { name: '是', value: '1', disabled: false },
        { name: '否', value: '0', disabled: false },
        { name: '非', value: '3' },
      ],
    },
    hooks: {},
  },
  {
    type: 'textarea',
    label: '文本框',
    key: 'textarea',
    required: true,
    comOption: {},
    hooks: {},
  },
  { type: 'gap' },
  {
    type: 'picker',
    label: '选择器-请求接口',
    key: 'picker',
    required: true,
    actions: '/kingon-system/dict/data/type/sys-educational-Level',
    // pam: {
    //   current: 1,
    //   size: 10
    // },
    comOption: {
      lableName: 'dictLabel',
      keyName: 'dictKey',
    },
    hooks: {},
  },
  {
    type: 'picker',
    label: '选择器-自定义数据',
    key: 'picker-dict',
    initVal: (formConfig) => {
      return '2';
    },
    required: true,
    // actions: '/kingon-system/dict/data/type/sys_zhsq_caseEventType',
    comOption: {
      columns: [
        [
          { label: '键盘', prop: '1' },
          { label: '显示屏', prop: '2' },
          { label: '主机', prop: '3' },
        ],
      ],
      lableName: 'label',
      keyName: 'prop',
    },
    hooks: {},
  },
  {
    type: 'picker',
    label: '选择器-自定义数据-没有回显',
    key: 'picker-no-init',
    comOption: {
      columns: [
        [
          { label: '键盘', prop: '1' },
          { label: '显示屏', prop: '2' },
          { label: '主机', prop: '3' },
        ],
      ],
      lableName: 'label',
      keyName: 'prop',
    },
    hooks: {},
  },
  { type: 'gap' },
  { type: 'title', label: 'Hooks 操作多个字段' },
  {
    type: 'picker',
    label: 'hooks 事件联动 - 联系人',
    key: 'hooks-link-1',
    required: false,
    // actions: '/kingon-system/dict/data/type/sys_zhsq_caseEventType',
    comOption: {
      columns: [
        [
          { name: '张三', phone: '19163686747' },
          { name: '李四', phone: '1888686747' },
          { name: '王五', phone: '17163686747' },
        ],
      ],
      lableName: 'name',
      keyName: 'name', // 提交到这个字段时用的key  // phone 已经在hooks中设置，这个字端根据实际需求应该提交 name
    },
    hooks: {
      // afterSetValue: ({ postValue, displayValue, origin, option }) => {
      //   console.log('consfig - hooks - afterSetValue:', { postValue, displayValue, origin, option });
      // },
      inChange: ({ formData, itemOption, data }, parent) => {
        console.log('consfig - hooks - inChange:', {
          formData,
          itemOption,
          data,
        });
        parent.refSetValue('hooks-link-2', {
          postValue: data.origin.phone,
          displayValue: data.origin.phone,
        });
      },
    },
  },
  {
    type: 'input',
    label: 'hooks 事件联动 - 联系电话',
    key: 'hooks-link-2',
    required: false,
    disabled: true,
    alert: {
      type: 'success',
      title: '',
      description: '适用于选择一个数据需要影响多个字段的场景',
      showIcon: false,
    },
  },
  {
    type: 'radio',
    label: 'hooks 事件联动 - 切换表单状态',
    key: 'hooks-link-change-opt',
    required: false,
    disabled: false,
    comOption: {
      columns: [
        { name: '隐藏', value: '1', disabled: false },
        { name: '显示', value: '0', disabled: false },
      ],
    },
    hooks: {
      inChange: ({ formData, itemOption, data }, parent) => {
        // console.log('consfig - hooks - inChange:', {
        //   formData,
        //   itemOption,
        //   data,
        // });
        parent.refSetItemOps('hooks-link-change-opt-1', {
          show: formData['hooks-link-change-opt'] != 1,
        });
      },
    },
    alert: {
      type: 'success',
      title: '',
      description:
        '适用于需要触发修改某个或多个表单项的配置的场景（如显隐/禁用其他表单项）',
      showIcon: false,
    },
  },
  {
    type: 'input',
    label: '我是会根据情况动态显隐的表单项',
    key: 'hooks-link-change-opt-1',
    placeholder: '请输入价格',
    required: true,
    comOption: {
      type: 'number',
    },
    hooks: {},
  },
  { type: 'gap' },
  {
    type: 'datetime-picker',
    label: '时间选择器',
    placeholder: '',
    key: 'datetime-picker',
    comOption: {
      mode: 'date',
      formatter: (type, value) => {
        if (type === 'year') {
          return `${value}年`
        }
        if (type === 'month') {
          return `${value}月`
        }
        if (type === 'day') {
          return `${value}日`
        }
        return value;
      },
    },
    hooks: {
      handleSetValue: ({ postValue, displayValue, origin, option}) => {
        console.log("handleSetValue ->", postValue, displayValue, origin, option);
        return [
          dayjs(postValue).format('YYYY年MM月DD日'), 
          dayjs(displayValue).format('YYYY年MM月DD日')
        ]
      },
    },
  },
  {
    type: 'datetime-picker',
    label: '服务时间(时间区域)',
    placeholder: '',
    required: true,
    key: 'datetime-picker-time-range',
    comOption: {
      mode: 'time-range',
    },
    hooks: {
      inChange: ({ formData, itemOption, data }, parent) => {
        // console.log('consfig - hooks - inChange:', { formData, itemOption, data });
        const { start_time, end_time } = data.origin;
        formData.startTime = start_time;
        formData.endTime = end_time;
      },
    },
  },
  {
    type: 'calendar-picker',
    label: '日期选择器',
    placeholder: '',
    key: 'calendar-picker',
    comOption: {},
  },
  {
    type: 'number-box',
    label: '步进器',
    key: 'number-box',
    required: true,
    initVal: 1,
    comOption: {},
    rules: [
      {
        type: 'number',
        required: true,
        message: '必填',
        trigger: 'blur',
      },
    ],
    hooks: {},
  },
  { type: 'gap' },
  {
    type: 'image-upload',
    label: '图片上传',
    key: 'image-upload',
    placeholder: '请选择图片',
    required: false,
    comOption: {
      autoUpload: true,
      action: uploadUrl,
    },
    hooks: {},
  },
  {
    type: 'voice-upload',
    label: '录音上传',
    key: 'voice-upload',
    placeholder: '请长按进行录音',
    required: false,
    comOption: {
      autoUpload: true,
      action: uploadUrl,
    },
    hooks: {},
  },
  {
    type: 'video-upload',
    label: '视频上传',
    key: 'video-upload',
    placeholder: '请进行录制或选择',
    required: false,
    comOption: {
      action: uploadUrl,
      config: {
        autoUpload: true,
      },
    },
    hooks: {},
  },
  {
    type: 'file-upload',
    label: '附件上传',
    key: 'file-upload',
    placeholder: '请进行选择',
    required: false,
    comOption: {
      action: uploadUrl,
      maxfile: 3,
    },
    hooks: {},
  },
  { type: 'gap' },
  { type: 'title', label: '分段标题' },
  {
    type: 'location',
    label: '定位获取',
    key: 'location',
    placeholder: '请进行定位获取',
    required: false,
    alert: {
      type: 'warning',
      title: '',
      description:
        '需要kingonx后端有地理位置逆编码接口，否则只返回经纬度（非APP平台）',
      showIcon: true,
    },
    comOption: {
      action: uploadUrl,
    },
    hooks: {},
  },
  {
    type: 'location',
    label: '打开地图选择位置',
    key: 'location-chooseLocation',
    placeholder: '打开地图选择位置',
    required: false,
    comOption: {
      mode: 'chooseLocation',
      action: uploadUrl,
    },
    hooks: {},
  },
  {
    type: 'tree-picker',
    label: '树结构选择器（如：楼栋数据/部门/区域）',
    key: 'tree-picker',
    placeholder: '选择抄送人',
    required: false,
    alert: {
      type: 'success',
      title: '提示',
      description:
        '部分接口返回的格式可能非标准树结构，需要通过lazyFun，配合children进行改动，如区域数据',
      showIcon: true,
    },
    comOption: {
      action: '/kingon-system/region/lazy-tree',
      // action: '/kingon-system/region/lazy-list',
      // action: '/kingon-mechanism/area/customLazyList',
      // action: "/kingon-system/dept/lazy-tree",
      // action: '/kingon-system/dept/parentDept',
      param: {
        // parentId: 0,
        parentCode: '00',
      },
      // 数据深度
      depth: 0,
      enableLazy: false,
      postKey: 'code',
      props: {
        label: 'title',
        children: 'children',
        multiple: false,
      },
      lazyFun: async (item, parenNode, index) => {
        console.log('lazyFun', { item, parenNode, index });
        // 自定义请求，并设置数据
        const reqConf = {
          url: '/kingon-system/region/lazy-tree',
          data: { parentCode: parenNode.id },
        };
        const { data } = await uni.$kui.request(reqConf);

        const treeData = data.map((item) => {
          if (!item.children) item.children = [];
          // 设置当前层级数据是否可选，（注意：设置成false，会往下触发）
          item.canSelect = true;
          // user 这个控制是否显示右边的右箭头按钮显示，<i v-if="!item.user"
          item.user = item.hasChildren === false ? true : false;
          return item;
        });
        parenNode.children = treeData;
      },
    },
    hooks: {
      inChange: ({ formData, itemOption, data }, parent) => {
        console.log('consfig - hooks - inChange:', {
          formData,
          itemOption,
          data,
        });
      },
    },
  },
  {
    type: 'tree-picker',
    label: '树结构选择器-部门选择',
    key: 'tree-picker-dept',
    placeholder: '选择部门',
    required: false,
    comOption: {
      action: '/kingon-system/dept/getDeptChildIds',
      // param: { parentId: 0 },
      // 数据深度
      depth: 0,
      enableLazy: false,
      postKey: 'id',
      props: {
        label: 'deptName',
        children: 'children',
        multiple: false,
        checkStrictly: false,
        nodes: false,
        // hasPath: false
      },
    },
    hooks: {},
  },
  {
    type: 'selector',
    label: '分页选择器-单选（如：员工）',
    key: 'selector-s',
    placeholder: '选择员工',
    required: false,
    comOption: {
      action: '/kingon-zhsq/personnelRecord/page',
      // param: { parentId: 0 },
      labelKey: ['personalPhotoUrl', 'name', 'jobName', 'jobName2'],
      labelType: ['avatar', 'text', 'text', 'text'],
      valueKey: 'id',
      searchKey: 'name',
      navigationBar: ['头像', '姓名', '员工类型', '员工类型2'],
      showNavigationBar: true,
      // placeholder:'',
      showSearch: true,
      showKey: 'name' /** 用于显示的key， 默认用于显示和提交的是valueKey */,
    },
    hooks: {
      inChange: ({ formData, itemOption, data }, parent) => {
        console.log('consfig - hooks - inChange:', {
          formData,
          itemOption,
          data,
        });
        parent.refSetValue('selector-s-change', {
          postValue: data.origin.item.contactNumber,
          displayValue: data.origin.item.contactNumber,
        });
      },
    },
  },
  {
    type: 'input',
    label: '员工联系电话',
    key: 'selector-s-change',
    required: true,
    disabled: true,
    rules: [{ required: true, message: '必填', trigger: 'blur' }],
    comOption: {
      type: 'number',
      'suffix-icon': 'phone',
      'suffix-icon-style': 'font-weight: bold;',
    },
  },
  {
    type: 'selector',
    label: '分页选择器-多选（如：员工）',
    key: 'selector-m',
    placeholder: '选择员工',
    required: true,
    comOption: {
      mode: 'multiple',
      action: '/kingon-system/page',
      // param: { parentId: 0 },
      labelKey: ['avatar', 'name', 'roleName'],
      labelType: ['avatar', 'text', 'tag'],
      valueKey: 'name', // 提交到后台的key
      searchKey: 'name',
      navigationBar: ['头像', '姓名', '员工类型'],
      showNavigationBar: true,
      // placeholder:'',
      showSearch: true,
      showKey: 'name',
    },
    hooks: {
      inChange: ({ formData, itemOption, data }, parent) => {
        console.log('consfig - hooks - inChange:', {
          formData,
          itemOption,
          data,
        });
        const ids = data.origin.map((v) => v.item.id).join(',');
        // parent.refSetValue("selector-m-name", {
        // 	postValue: data.origin.phone,
        // 	displayValue: data.origin.phone,
        // });
        // 如果该值非配置项。可以直接通过 formData 修改;
        formData['selector-m-ids'] = ids;
      },
    },
  },
  {
    type: 'selector',
    label: '分页选择器-列表项为字典值',
    key: 'selector-dict',
    placeholder: '选择特殊人员',
    required: true,
    comOption: {
        action: '/kingon-zhsq/communityPopulation/page',
        // param: { parentId: 0 },
        labelKey: ['name', 'specialPopulationType'],
        labelType: ['text', 'tag'],
        valueKey: 'name',
        searchKey: 'masterName',
        navigationBar: ['姓名', '人员类型'],
        showNavigationBar: true,
        placeholder: '输入户主名称搜索',
        showSearch: true,
        showKey: 'name',
        format: (keyName, value, type) => {
          // return this.dict('sys_tstatus_zhsq', value);
          console.log("xxx --- this", this);
          return this.dictArray('special_person_type', value).join(' | ');
        },
    },
    hooks: {
      inChange: ({ formData, itemOption, data }, parent) => {
        console.log('consfig - hooks - inChange:', {
          formData,
          itemOption,
          data,
        });
        const ids = data.origin.map((v) => v.item.id).join(',');
        // parent.refSetValue("selector-m-name", {
        // 	postValue: data.origin.phone,
        // 	displayValue: data.origin.phone,
        // });
        // 如果该值非配置项。可以直接通过 formData 修改;
        formData['selector-m-ids'] = ids;
      },
    },
  },
  {
    type: 'custom',
    label: '自定义',
    key: 'custom',
    placeholder: '',
    required: false,
    /** 自己定义的数据 */
    cusType: 'switch',
    comOption: {},
    hooks: {},
  },
  {
    type: 'rate',
    label: '评分',
    key: 'rate-1',
    required: true,
    rules: [
      {
        type: 'number',
        required: true,
        message: '请选择评分',
        trigger: 'blur',
      },
    ],
    comOption: {
      size: 25,
    },
    hooks: {},
  },
  {
    type: 'input',
    label: '有默认值且不显示的表单项(测试初始化值是否生效)',
    key: 'input_have_default',
    disabled: false,
    required: true,
    // initVal: '这是设置的默认值',
    show: false,
    initVal: 1,
  }
];

/**
 *
 * 钩子以及顺序 （从上到下）
 * hooks:
 *   -  handleSetValue({ postValue, displayValue, origin, option}) // 数值设置钩子
 *   -  inChange({ postValue, displayValue, origin, option}) // 数值设置钩子
 */

export default () => config;
